from django.shortcuts import redirect, render, HttpResponse
from rbac.service.init_permission import init_permission

from rbac import models


def login(request):
    if request.method == 'GET':
        return render(request, "login.html")

    # 获取用户名和密码
    name = request.POST.get("user")
    pwd = request.POST.get("pwd")

    # 用户名或密码为空不能访问
    if not all([name, pwd]):
        return render(request, "login.html", {"error": "用户名或密码不能为空"})

    # 查询数据库用户是否存在
    user_obj = models.UserInfo.objects.filter(name=name, password=pwd).first()
    if not user_obj:
        return render(request, "login.html", {"error": "用户名或密码错误"})

    # 权限信息初始化
    init_permission(request, user_obj)

    return redirect("/customer/list/")